<?php
namespace app\task;

use Redis\QueueModel;
use think\Config;
use think\Exception;
use think\exception\DbException;
use think\Log;
use think\Model;
use think\Queue;
use app\admin\model\Prize;

/**
 * 单控自动关闭
 * Class LoopGame
 * @package app\task
 */
class CreateOpenPrizeList{


    public static function fire()
    {
        $time = date('His');

        try {
            $prizeModel = new Prize();
            //$prizeModel->execute("SELECT 1"); // 查询一次SQL 保持连接*

            $queueRedis = QueueModel::getInstance();

        }catch (\RedisException $e){
            $msg = 'redis:' . $e->getMessage();
            Log::info($msg);
            return false;
        }catch (Exception $e){
            $msg = $e->getMessage();
            Log::info($msg);
            return false;
        }

        //每天 00时10分00秒 执行
        if ($time != 000500)
        {
            //每隔四个小时查询一次 防止mysql连接挂掉
            if (in_array($time,['000000','040000','080000','120000','160000','200000'])){
                // 查询一次SQL,判断连接是否正常
                $prizeModel->execute("SELECT 1");
            }
            return true;
        }

        //开奖任务
        $job = 'OpenPrize';
        //任务队列名
        $queue = 'openprize';

        //删除全部任务
        $queueRedis->remQueueAll($queue);

        //读取抽奖列表 获取当日开奖要开奖的数据列表 (当前时间开始)
        $end = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $map = [
            'switch' => 1,
            'opentime' => ['BETWEEN',[time(),$end]],
        ];

        $prizeList = collection($prizeModel
            ->field('id,name,starttime,endtime,opentime,switch,total,num,is_level')
            ->where($map)
            //->whereTime('opentime','today')
            ->order('opentime asc')
            ->select())->toArray();

        if (!$prizeList){
            $msg = "Not Data!";
            Log::info($msg);
            return false;
        }

        //设置延时开奖 成功 失败的记录
        $successList = $errorList = [];

        foreach ($prizeList as $k => $v){

            //未超过开奖时间的记录加入延时开奖
            if ($v['opentime'] > time()){
                //计算延时执行的时间
                $delay = $v['opentime'] - time();
                //延时加入队列
                $isPushed = Queue::later($delay,$job,$v,$queue);

                //判断是否是最后一个开奖发红包
                if ($k == (count($prizeList) - 1)){
                    self::sendRedPacket($v,$queueRedis);
                }

                //记录成功 失败的记录
                if( $isPushed !== false ){
                    $successList[] = $v;
                }else{
                    $errorList[] = $v;
                }

            }else{
                $errorList[] = $v;
            }
        }

        $total = count($successList);

        $msg = "OpenPrize Successed. Sum:" . $total;
        Log::info($msg);

        return true;
    }

    public static function sendRedPacket($data,$queueRedis)
    {
        $job = 'RedPacket';
        $queue = 'redpacket';
        //删除全部任务
        $queueRedis->remQueueAll($queue);

        if (Config::get('site.noprize_redpacket')){
            //最后一次开奖 5分钟后发红包 防止未全部开奖
            $delay = $data['opentime'] + 300 - time();
            $expire_redpacket = Config::get('site.expire_redpacket');
            $param = [
                'send_time'     => $data['opentime'],
                'expire_redpacket'    => $expire_redpacket,
            ];
            //延时加入队列
            $isPushed = Queue::later($delay,$job,$param,$queue);
        }

        return true;
    }

}